package com.cuit.jifver.weibo.activity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;


import com.cuit.jifver.weibo.data.ConfigUtil;
import com.cuit.jifver.weibo.data.Weibo;
import com.cuit.jifver.weibo.data.WeiboException;
import com.cuit.jifver.weibo.data.WeiboParameters;
import com.cuit.jifver.weibo.net.AccessToken;
import com.cuit.jifver.weibo.net.AsyncWeiboRunner;
import com.cuit.jifver.weibo.net.Utility;
import com.cuit.jifver.weibo.net.AsyncWeiboRunner.RequestListener;
import com.cuit.jifver.weibo.util.Constants;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


/**
 * 展示AccessToken
 * 
 * 1. 获取授权后成功后回调的URL并匹配出验证码 （网易无验证码不处理） 2.获取OAuth对象并设置验证码 3.获取accessToken
 * 
 * @author bywyu
 * 
 */
public class ShowAccessTokenAct extends Activity implements RequestListener
{
	private static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;
	private final String LOGTAG = "ShowAccessTokenAct";
	
	private String mPicPath = "";
	private String status = "";
	Weibo mWeibo = Weibo.getInstance();
	ConfigUtil configUtil = ConfigUtil.getInstance();
	AccessToken accessToken = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shared_showaccesstoken_ui);
		String oauth_verifier = "";
		
		// 匹配验证码
		if (!ConfigUtil.getInstance().getCurWeibo().equals(ConfigUtil.WANGYIW))
		{
			String url = getIntent().getStringExtra(ConfigUtil.OAUTH_VERIFIER_URL);
			Log.e(LOGTAG, "url=" + url);
			if (url != null)
			{
				Uri uri = Uri.parse(url);
				oauth_verifier = uri.getQueryParameter(configUtil.getVerifierName());
			}
		}
			
		
		TextView textView = (TextView) findViewById(R.id.accessTokenView);
		textView.setTextColor(Color.RED);
		textView.setTextSize(20);
		textView.setText(oauth_verifier);
		
		final EditText ed = (EditText) this.findViewById(R.id.content);
		
		mWeibo.addOauthverifier(oauth_verifier);
		Log.e(LOGTAG, "starting request accesstoken");
		try {
		accessToken =	mWeibo.generateAccessToken(this, null);
		Log.e(LOGTAG, "xiao_accesstoken="+accessToken.getToken()+"_xiao_accesstokenSecrect="+accessToken.getSecret());
		} catch (WeiboException e1) {
			e1.printStackTrace();
		}
		Log.e(LOGTAG, "end request accesstoken");
		
		if (accessToken != null)
		{
			saveAccessToken(accessToken);
		}
		
		
		
		Button button = (Button) this.findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				File file = Environment.getExternalStorageDirectory();
				String sdPath = file.getAbsolutePath();
				mPicPath = sdPath + "/" + "abc.jpg";
				
				Weibo weibo = Weibo.getInstance();
				try {
					Log.e("", "" + (weibo.getAccessToken() == null));
					if (!TextUtils.isEmpty((String) (weibo.getAccessToken().getToken()))) {
						if (!TextUtils.isEmpty(mPicPath)) {
							status = ed.getText().toString();
							//upload(weibo, Weibo.APP_KEY, ShowAccessTokenAct.this.mPicPath, status, "", "");
							upload(weibo, Weibo.APP_KEY, ShowAccessTokenAct.this.mPicPath, status, "", "");
							
						}
						else {
							// Just update a text weibo!
							status = ed.getText().toString();
							update(weibo, Weibo.APP_KEY, status, "", "");
						}
					}
					else {
						Toast.makeText(ShowAccessTokenAct.this, ShowAccessTokenAct.this.getString(R.string.please_login), Toast.LENGTH_LONG);
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private String upload(Weibo weibo, String source, String file, String status, String lon, String lat) throws WeiboException {
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		//bundle.add("pic", file);
		bundle.add("status", status);
		if (!TextUtils.isEmpty(lon)) {
			bundle.add("lon", lon);
		}
		if (!TextUtils.isEmpty(lat)) {
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/upload.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
		
		return rlt;
	}
	
	private String update(Weibo weibo, String source, String status, String lon, String lat) throws MalformedURLException, IOException, WeiboException {
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		bundle.add("status", status);
		if (!TextUtils.isEmpty(lon)) {
			bundle.add("lon", lon);
		}
		if (!TextUtils.isEmpty(lat)) {
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/update.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
		return rlt;
	}
	
	@Override
	public void onComplete(String response) {
		Log.e("", "onComplete:" + response);
		Toast.makeText(this, R.string.send_sucess, Toast.LENGTH_LONG);
		this.finish();
	}
	
	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onError(WeiboException e) {
		Toast.makeText(this, String.format(this.getString(R.string.send_failed) + ":%s", e.getMessage()), Toast.LENGTH_LONG);
	}
	
	
	private void saveAccessToken(AccessToken token)
	{
		SharedPreferences preferences = getSharedPreferences(Constants.oauth.OAUTH_FILE_NAME, MODE);
		Editor editor = preferences.edit();
		editor.putString(ConfigUtil.access_token_name, token.getToken());
		editor.putString(ConfigUtil.access_token_secret_name, token.getSecret());
		editor.commit();
	}
}
